package service

import (
	"bytes"
	"context"
	"encoding/json"
	"video_src/basic/appConfig"
	__ "video_src/basic/proto"
	"video_src/handler/models"

	"github.com/elastic/go-elasticsearch/v7/esapi"
	"log"
	"strconv"
	"sync"
)

func (s *Server) SyncToEs(_ context.Context, in *__.SyncToEsReq) (*__.SyncToEsResp, error) {
	var videosList []models.Video
	query := appConfig.DB
	if in.VideoId != 0 {
		query = query.Where("id=?", in.VideoId)
	}
	query.Find(&videosList)

	SyncVideoToEs(videosList)

	return &__.SyncToEsResp{}, nil
}

func SyncVideoToEs(videosList []models.Video) {
	var wg sync.WaitGroup
	for _, videos := range videosList {
		wg.Add(1)

		go func(videos models.Video) {
			defer wg.Done()

			// Build the request body.
			data, err := json.Marshal(videos)
			if err != nil {
				log.Fatalf("Error marshaling document: %s", err)
			}

			// Set up the request object.
			req := esapi.IndexRequest{
				Index:      "videos",
				DocumentID: strconv.Itoa(int(videos.ID)),
				Body:       bytes.NewReader(data),
				Refresh:    "true",
			}

			// Perform the request with the client.
			res, err := req.Do(context.Background(), appConfig.EsClient)
			if err != nil {
				log.Fatalf("Error getting response: %s", err)
			}
			defer res.Body.Close()

		}(videos)
	}
	wg.Wait()
}
